<template>
	<view class="container">
		<view class="header">
			<text class="header-title">{{ scriptName }}</text>
		</view>
		
		<view class="main-content">
			<scroll-view class="characters-content" scroll-y>
				<view class="characters-list">
					<view v-for="character in selectedCharacters" :key="character.id" class="character-section">
						<view class="character-card">
							<image class="character-avatar" :src="character.avatar" mode="aspectFill"></image>
							<view class="character-info">
								<text class="character-name">{{ character.name }}</text>
								<text v-if="character._id !== 'host'" class="character-age">{{ character.age }}岁</text>
								<text class="character-personality">{{ character.personality }}</text>
							</view>
						</view>
						
						<view class="script-input-section">
							<textarea
								class="script-input"
								v-model="character.script"
								placeholder="请输入该角色的剧本内容"
								maxlength="1000000"
							></textarea>
							<button class="upload-btn" @click="uploadScript(character.id)">
								<text class="upload-btn-text">上传剧本</text>
							</button>
						</view>
					</view>
				</view>
			</scroll-view>
			
			<view class="performance-panel">
				<text class="section-title">表演文字</text>
				<scroll-view class="performance-content" scroll-y>
					<view v-for="dialogue in performanceDialogues" :key="dialogue._id" class="performance-item" :class="{ 'host-message': dialogue.player.player_id === 'host', 'player-message': dialogue.player.player_id !== 'host' }">
						<image class="message-avatar" :src="dialogue.player.avatar" mode="aspectFill"></image>
						<view class="message-content">
							<text class="message-name">{{ dialogue.player.name }}</text>
							<view class="message-bubble">
								<text class="message-text">{{ dialogue.content }}</text>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		
		<button 
				class="start-btn" 
				:class="{ 'disabled': !canStartPerformance }"
				@click="togglePerformance"
			>
				{{ isPerforming ? '停止演绎' : '开始演绎' }}
			</button>
	</view>
</template>

<script>
	import { hostChat, chat } from '@/api/coze.js'

	export default {
		data() {
			return {
				selectedCharacters: [],
				testId: '',
				isPerforming: false,
				scriptName: '',
				performanceDialogues: [], // 新增表演对话记录数组
				host: {
					_id: 'host',
					name: '主持人',
					avatar: '/static/avatars/host.jpeg',
					script: '',
					performance: ''
				}
			}
		},
		computed: {
			playerCount() {
				// 计算玩家人数，不包括主持人
				return this.selectedCharacters.filter(char => char._id !== 'host').length
			},
			canStartPerformance() {
				// 检查是否所有角色都已经设置了剧本
				return this.selectedCharacters.every(char => char.script.trim() !== '')
			}
		},
		async onLoad(option) {
			// 获取测试记录ID
			this.testId = option.testId
			if (!this.testId) {
				uni.showToast({
					title: '缺少测试记录ID',
					icon: 'none'
				})
				return
			}
			
			try {
				// 先获取测试记录
				const db = uniCloud.database()
				const testRecord = await db.collection('script_test').doc(this.testId).get()
				
				if (!testRecord.result.data || !testRecord.result.data.length) {
					throw new Error('未找到测试记录')
				}
				
				// 获取剧本名称和测试状态
				const currentTest = testRecord.result.data[0]
				this.scriptName = currentTest.script_name
				this.canContinuePerformance = currentTest.status === 0 // 状态为进行中时可继续
				
				// 获取选中角色的ID数组
				const selectedIds = currentTest.selected_players.map(player => player.player_id)
				
				// 从数据库获取选中角色的完整信息
				const res = await db.collection('script_player').where({
					_id: db.command.in(selectedIds)
				}).get()
				
				if (res.result && res.result.data && res.result.data.length > 0) {
					// 为每个角色添加script和performance属性
					this.selectedCharacters = [this.host, ...res.result.data.map(char => ({
						...char,
						script: '',
						performance: ''
					}))]
					
					// 获取每个角色已保存的剧本内容
					const dialogueRes = await db.collection('script_test_dialogue').where({
						test_id: this.testId,
						type: 'script'
					}).get()
					
					if (dialogueRes.result && dialogueRes.result.data) {
						// 遍历每个角色，找到对应的剧本内容
						this.selectedCharacters.forEach(char => {
							const dialogue = dialogueRes.result.data.find(d => 
								d.player.player_id === char._id
							)
							if (dialogue) {
								char.script = dialogue.content
							}
						})
					}
					
					// 获取所有表演对话记录
					const performanceRes = await db.collection('script_test_dialogue').where({
						test_id: this.testId,
						type: 'speak'
					}).orderBy('create_time', 'asc').get()
					
					if (performanceRes.result && performanceRes.result.data) {
						// 更新performanceDialogues数组
						this.performanceDialogues = performanceRes.result.data;
						
						// 遍历每个角色，更新其最新的表演内容
						performanceRes.result.data.forEach(dialogue => {
							const character = this.selectedCharacters.find(char => 
								char._id === dialogue.player.player_id
							)
							if (character) {
								character.performance = dialogue.content
							}
						})
					}
				} else {
					uni.showToast({
						title: '未找到选中的角色数据',
						icon: 'none'
					})
				}
			} catch (e) {
				console.error('加载数据失败:', e)
				uni.showToast({
					title: `加载失败: ${e.message || '未知错误'}`,
					icon: 'none',
					duration: 2000
				})
			}
		},
		computed: {
			canStartPerformance() {
				// 检查是否所有角色都已经设置了剧本
				return this.selectedCharacters.every(char => char.script.trim() !== '')
			}
		},
		methods: {
			uploadScript(characterId) {
				// 调用系统文件选择
				uni.chooseFile({
					count: 1, // 限制只能选择一个文件
					extension: ['.txt'], // 限制文件类型为txt
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						// 读取文件内容
						plus.io.resolveLocalFileSystemURL(tempFilePath, (entry) => {
							entry.file((file) => {
								const reader = new plus.io.FileReader();
								reader.onloadend = (e) => {
									// 找到对应的角色并更新其剧本内容
									const character = this.selectedCharacters.find(char => char._id === characterId);
									if (character) {
										character.script = e.target.result;
									}
								};
								reader.readAsText(file, 'utf-8');
							});
						}, (error) => {
							console.error('读取文件失败:', error);
							uni.showToast({
								title: '读取文件失败',
								icon: 'none'
							});
						});
				},
				fail: (err) => {
					console.error('选择文件失败:', err);
					uni.showToast({
						title: '选择文件失败',
						icon: 'none'
					});
				}
				});
			},
			async togglePerformance() {
				if (this.isPerforming) {
					// 停止演绎
					this.isPerforming = false;
					uni.showToast({
						title: '已停止演绎',
						icon: 'success'
					});
					return;
				}

				if (!this.canStartPerformance) return;
				
				try {
					const db = uniCloud.database()
					const currentTime = Date.now()
					
					// 为每个角色处理剧本对话记录
					const dialoguePromises = this.selectedCharacters.map(async character => {
						// 查询是否已存在该角色的剧本记录
						const existingRecord = await db.collection('script_test_dialogue')
							.where({
								test_id: this.testId,
								'player.player_id': character._id,
								type: 'script'
							})
							.get()
						
						if (existingRecord.result.data && existingRecord.result.data.length > 0) {
							// 更新现有记录
							return db.collection('script_test_dialogue')
								.doc(existingRecord.result.data[0]._id)
								.update({
									content: character.script || '暂无剧本内容',
									update_time: currentTime
								})
						} else {
							// 创建新记录
							return db.collection('script_test_dialogue').add({
								test_id: this.testId,
								player: {
									player_id: character._id,
									name: character.name,
									avatar: character.avatar
								},
								content: character.script || '暂无剧本内容',
								target: 'all',
								type: 'script',
								create_time: currentTime
							})
						}
					})
					
					await Promise.all(dialoguePromises)
					this.isPerforming = true;
					
					// 获取主持人的剧本内容
					const hostScript = this.selectedCharacters.find(char => char._id === 'host')?.script;
					if (hostScript) {
						try {
							// 获取测试记录中的conversationId
							const testRecord = await db.collection('script_test').doc(this.testId).get()
							const currentTest = testRecord.result.data[0]
							const conversationId = currentTest.conversationId
							
							console.log('当前会话ID:', conversationId)
							
							// 调用chat方法并传入conversationId
							const chatResult = await hostChat(hostScript, 
								// 处理消息回调
								(content) => {
									// 更新主持人的表演内容
									const host = this.selectedCharacters.find(char => char._id === 'host');
									if (host) {
										host.performance = content;
									}
								},
								conversationId
							);
							
							console.log('chat返回结果:', chatResult)
							
							// 将主持人的完整对话保存到数据库
							const host = this.selectedCharacters.find(char => char._id === 'host');
							if (host && host.performance) {
								const db = uniCloud.database();
								db.collection('script_test_dialogue').add({
									test_id: this.testId,
									player: {
										player_id: host._id,
										name: host.name,
										avatar: host.avatar
									},
									content: host.performance,
									target: 'all',
									type: 'speak',
									create_time: Date.now()
								}).catch(err => {
									console.error('保存主持人对话失败:', err);
								});
							}
							
							// 更新会话ID到数据库
							if (chatResult.conversationId) {
								console.log('准备更新会话ID:', {
									testId: this.testId,
									newConversationId: chatResult.conversationId
								})
								
								try {
									const updateResult = await db.collection('script_test').doc(this.testId).update({
										conversationId: chatResult.conversationId
									})
									console.log('更新会话ID结果:', updateResult)
								} catch (updateError) {
									console.error('更新会话ID失败:', updateError)
									throw updateError
								}
							} else {
								console.error('未获取到有效的会话ID')
							}
							
							// 显示成功提示
							uni.showToast({
								title: '开始演绎',
								icon: 'success'
							});

							// 主持人对话完成后，依次处理每个玩家的对话
							const players = this.selectedCharacters.filter(char => char._id !== 'host');
							for (const player of players) {
								try {
									// 调用chat方法处理玩家对话
									const playerChatResult = await chat(player.script,
										// 处理消息回调
										(content) => {
											// 更新玩家的表演内容
											player.performance = content;
										},
										chatResult.conversationId
									);

									// 将玩家的对话保存到数据库
									if (player.performance) {
										await db.collection('script_test_dialogue').add({
											test_id: this.testId,
											player: {
												player_id: player._id,
												name: player.name,
												avatar: player.avatar
											},
											content: player.performance,
											target: 'all',
											type: 'speak',
											create_time: Date.now()
										});
									}
								} catch (playerError) {
									console.error(`处理玩家 ${player.name} 的对话失败:`, playerError);
								}
							}
						} catch (error) {
							console.error('调用AI服务失败:', error);
							uni.showToast({
								title: '调用AI服务失败',
								icon: 'none'
							});
						}
					}
				} catch (e) {
					console.error('创建剧本对话记录失败:', e)
					uni.showToast({
						title: '创建记录失败',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style>
.container {
	min-height: 100vh;
	position: relative;
}

.container::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), url('/static/bg.png') no-repeat center center;
	background-size: cover;
	z-index: -1;
}

.header {
	padding: 60rpx 40rpx;
	text-align: center;
}

.header-title {
	font-size: 48rpx;
	color: #ffffff;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.header-subtitle {
	font-size: 36rpx;
	color: #ffffff;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.header-info {
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.8);
}

.main-content {
	display: flex;
	height: calc(100vh - 280rpx);
	padding: 30rpx;
}

.characters-content {
	flex: 0.4;
	margin-right: 30rpx;
	display: flex;
	flex-direction: column;
}

.characters-list {
	width: 100%;
}

.character-section {
	width: 100%;
	margin-bottom: 40rpx;
	background: rgba(255, 255, 255, 0.15);
	border-radius: 20rpx;
	padding: 30rpx;
}

.character-card {
	display: flex;
	align-items: flex-start;
	margin-bottom: 30rpx;
	padding-bottom: 20rpx;
	border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.character-avatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	margin-right: 20rpx;
}

.character-info {
	flex: 1;
}

.character-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
	display: block;
	margin-bottom: 8rpx;
}

.character-age {
	font-size: 26rpx;
	color: rgba(255, 255, 255, 0.8);
	display: block;
	margin-bottom: 8rpx;
}

.character-personality {
	font-size: 26rpx;
	color: rgba(255, 255, 255, 0.8);
	display: block;
}

.script-input-section {
	margin-bottom: 20rpx;
}

.script-input {
	width: 100%;
	height: 600rpx;
	background: rgba(255, 255, 255, 0.1);
	border-radius: 10rpx;
	padding: 20rpx;
	color: #ffffff;
	font-size: 28rpx;
	margin-bottom: 20rpx;
	overflow-y: auto;
	word-wrap: break-word;
	white-space: pre-wrap;
}

.upload-btn {
	background: rgba(255, 255, 255, 0.2);
	border-radius: 10rpx;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
}

.upload-btn-text {
	color: #ffffff;
	font-size: 28rpx;
}

.performance-panel {
	flex: 0.6;
	background: rgba(0, 0, 0, 0.2);
	border-radius: 20rpx;
	padding: 30rpx;
	display: flex;
	flex-direction: column;
}

.performance-content {
	flex: 1;
	overflow-y: auto;
	padding: 20rpx;
}

.performance-item {
	display: flex;
	margin-bottom: 30rpx;
	position: relative;
}

.host-message {
	flex-direction: row;
}

.player-message {
	flex-direction: row-reverse;
}

.message-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin: 0 20rpx;
}

.message-content {
	max-width: 70%;
}

.message-name {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.7);
	margin-bottom: 8rpx;
}

.host-message .message-name {
	text-align: left;
}

.player-message .message-name {
	text-align: right;
}

.message-bubble {
	padding: 20rpx;
	border-radius: 12rpx;
	position: relative;
}

.host-message .message-bubble {
	background-color: rgba(255, 255, 255, 0.1);
	border-top-left-radius: 4rpx;
}

.player-message:nth-child(8n+1) .message-bubble {
	background-color: rgba(100, 149, 237, 0.8); /* 矢车菊蓝 */
	border-top-right-radius: 4rpx;
}

.player-message:nth-child(8n+2) .message-bubble {
	background-color: rgba(147, 112, 219, 0.8); /* 中紫色 */
	border-top-right-radius: 4rpx;
}

.player-message:nth-child(8n+3) .message-bubble {
	background-color: rgba(70, 130, 180, 0.8); /* 钢青色 */
	border-top-right-radius: 4rpx;
}

.player-message:nth-child(8n+4) .message-bubble {
	background-color: rgba(72, 209, 204, 0.8); /* 绿松石色 */
	border-top-right-radius: 4rpx;
}

.player-message:nth-child(8n+5) .message-bubble {
	background-color: rgba(65, 105, 225, 0.8); /* 皇家蓝 */
	border-top-right-radius: 4rpx;
}

.player-message:nth-child(8n+6) .message-bubble {
	background-color: rgba(138, 43, 226, 0.8); /* 紫罗兰色 */
	border-top-right-radius: 4rpx;
}

.player-message:nth-child(8n+7) .message-bubble {
	background-color: rgba(32, 178, 170, 0.8); /* 浅海洋绿 */
	border-top-right-radius: 4rpx;
}

.player-message:nth-child(8n+8) .message-bubble {
	background-color: rgba(123, 104, 238, 0.8); /* 中板岩蓝 */
	border-top-right-radius: 4rpx;
}

.message-text {
	color: #FFFFFF;
	font-size: 28rpx;
	line-height: 1.4;
	word-break: break-all;
}

.start-btn {
	width: 100%;
	background-color: #007AFF;
	color: #FFFFFF;
	border-radius: 10rpx;
	font-size: 28rpx;
	padding: 15rpx 0;
	margin: 20rpx 0;
}

.start-btn.disabled {
	background: rgba(255, 255, 255, 0.3);
	color: rgba(255, 255, 255, 0.5);
}

/* 适配H5端 */
@media screen and (min-width: 768px) {
	.performance-panel {
		flex: 0.6;
	}
}
</style>